package com.tanhua.sso.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tanhua.sso.config.HuanXinConfig;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Service
public class HuanXinTokenService {

    private static final ObjectMapper MAPPER = new ObjectMapper();

    @Autowired
    private HuanXinConfig huanXinConfig;

    @Autowired
    private RestTemplate restTemplate;

    //定义一个redis键名
    public static final String REDIS_KEY = "HX_TOKEN";

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 当redis中没有token值时, 执行这里的方法获取token值,并将数据保存到redis中
     * @return
     */
    private String refreshToken() {
        //获取token的url
        String targetUrl = this.huanXinConfig.getUrl() +
                this.huanXinConfig.getOrgName() + "/" + this.huanXinConfig.getAppName() + "/token";

        //填写请求参数集合(环信的要求)
        Map<String, String> param = new HashMap<>();
        param.put("grant_type", "client_credentials");
        param.put("client_id", this.huanXinConfig.getClientId());
        param.put("client_secret", this.huanXinConfig.getClientSecret());

        //请求环信接口  返回一个响应
        ResponseEntity<String> responseEntity =
                this.restTemplate.postForEntity(targetUrl, param, String.class);

        //如果返回状态码不为200 代表不成功,返回一个null
        if (responseEntity.getStatusCodeValue() != 200) {
            return null;
        }
        //返回成功
        String body = responseEntity.getBody();
        try {
            JsonNode jsonNode = MAPPER.readTree(body);
            //从redis中获取值
            String accessToken = jsonNode.get("access_token").asText();
            //判断值是否不为空
            if (StringUtils.isNotBlank(accessToken)) {
                // 是,则将token保存到redis，有效期为5天，环信接口返回的有效期为6天
                this.redisTemplate.opsForValue().set(REDIS_KEY, accessToken, Duration.ofDays(5));
                //返回保存的value
                return accessToken;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 获取token信息
     * @return
     */
    public String getToken() {
        //从redis中获取token信息
        String token = this.redisTemplate.opsForValue().get(REDIS_KEY);
        //判断是否为空
        if (StringUtils.isBlank(token)) {
            //为空则调用refreshToken方法
            return this.refreshToken();
        }
        //不为空则讲查找出来的值返回
        return token;
    }
}
